package com.googlecode.connectlet.tsa;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.connectlet.util.ByteArrayQueue;
import com.googlecode.connectlet.util.ClassPath;
import com.googlecode.connectlet.util.Streams;
import com.googlecode.connectlet.util.secure.CertKey;

public class TsaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private CertKey certKey;

	@Override
	public void init() {
		String keystoreFile = getInitParameter("keystoreFile");
		File keystore = new File(keystoreFile);
		if (!keystore.isAbsolute()) {
			keystore = ClassPath.getInstance("../" +
					getInitParameter("keystoreFile"));
		}
		try {
			certKey = new CertKey(keystore, getInitParameter("keystorePass"),
					getInitParameter("keystoreType"));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		ByteArrayQueue baq = new ByteArrayQueue();
		Streams.copy(req.getInputStream(), baq.getOutputStream());
		TimeStampReq tsReq = new TimeStampReq(baq.array(),
				baq.offset(), baq.length());
		TstInfo tstInfo = new TstInfo(new MessageImprint(tsReq), new Date());
		byte[] encodedResp = new TimeStampResp(tstInfo, certKey).getEncoded();
		resp.setContentType("application/timestamp-reply");
		resp.getOutputStream().write(encodedResp);
	}
}